﻿using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SocketClient : MonoBehaviour
{
    private Socket clientSocket;
    private byte[] buffer = new byte[1024];

    private void Start()
    {
        // 创建Socket客户端
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // 服务器的IP地址和端口号
        IPAddress serverIP = IPAddress.Parse("服务器IP地址");
        int serverPort = 12345; // 替换为实际的端口号

        // 连接到服务器
        try
        {
            clientSocket.Connect(new IPEndPoint(serverIP, serverPort));
            Debug.Log("连接服务器成功！");
        }
        catch (Exception ex)
        {
            Debug.LogError("连接服务器失败：" + ex.Message);
        }

        // 开始异步接收服务器的数据
        clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
    }

    private void Update()
    {
        // 在Update方法中可以处理与服务器的交互逻辑
        // 例如发送数据到服务器
        if (Input.GetKeyDown(KeyCode.Space))
        {
            string messageToSend = "Hello, Server!";
            byte[] data = Encoding.UTF8.GetBytes(messageToSend);
            clientSocket.Send(data);
        }
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        // 异步接收数据完成后的回调函数
        int bytesRead = clientSocket.EndReceive(ar);
        if (bytesRead > 0)
        {
            string receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Debug.Log("收到服务器消息: " + receivedMessage);

            // 继续异步接收下一条消息
            clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
        }
    }

    private void OnDestroy()
    {
        // 在销毁时关闭Socket连接
        if (clientSocket != null && clientSocket.Connected)
        {
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
    }
}